/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.zx.course.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.jms.Queue;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.common.lang.DateUtils;
import com.jeesite.modules.zx.question.bank.entity.TquestionBank;
import com.jeesite.modules.zx.question.bank.service.TquestionBankService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.utils.excel.annotation.ExcelField.Type;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.modules.app.util.wx.NioWebSocketHandler;
import com.jeesite.modules.app.util.wx.SocketMessage;
import com.jeesite.modules.sys.entity.Area;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.Post;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.AreaService;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.PostService;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.zx.course.authorization.entity.TcourseAuthorization;
import com.jeesite.modules.zx.course.authorization.service.TcourseAuthorizationService;
import com.jeesite.modules.zx.course.entity.Tcourses;
import com.jeesite.modules.zx.course.service.TcoursesService;
import com.jeesite.modules.zx.sys.msg.push.entity.ZxMsgPush;
import com.jeesite.modules.zx.sys.msg.push.service.ZxMsgPushService;
import com.jeesite.modules.zx.user.entity.ZxUser;
import com.jeesite.modules.zx.user.service.ZxUserService;

/**
 * 课程表Controller
 * @author zpp
 * @version 2020-01-19
 */
@Controller
@RequestMapping(value = "${adminPath}/zx/course/tcourses")
public class TcoursesController extends BaseController {

	@Autowired
	private TcoursesService tcoursesService;
	@Autowired
	private ZxUserService zxUserService;
	@Autowired
	private TcourseAuthorizationService tcourseAuthorizationService;
	@Autowired
	private PostService postService;
	@Autowired
	private ZxMsgPushService zxMsgPushService;
	@Autowired
	private UserService userService;
	@Autowired
    private Queue queue;
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

	@Autowired
	private TquestionBankService tquestionBankService;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Tcourses get(String id, boolean isNewRecord) {
		return tcoursesService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("zx:course:tcourses:view")
	@RequestMapping(value = {"list", ""})
	public String list(Tcourses tcourses, Model model) {
		model.addAttribute("tcourses", tcourses);
		return "modules/zx/course/tcoursesList";
	}
	@RequestMapping(value = {"listUser", ""})
	public String listUser(Tcourses tcourses, Model model) {
		TcourseAuthorization authCourse=new TcourseAuthorization();
		authCourse.setCourseId(tcourses.getId());
		List<TcourseAuthorization> findList = tcourseAuthorizationService.findList(authCourse);
		List<String> userIds=new ArrayList<>();
		JSONObject json=new JSONObject();
		for(TcourseAuthorization auth:findList){			
			String userId = auth.getUserId();
			User userSelect= userService.get(userId);
			if(userSelect!=null){
				String json2 = JsonMapper.toJson(userSelect);
				JSONObject parseObject = JSONObject.parseObject(json2);
				json.put(userId,parseObject);
			}
		}
		String selectDataJson = EncodeUtils.decodeUrl(json.toJSONString());
		if (JsonMapper.fromJson(selectDataJson, Map.class) != null){
			model.addAttribute("selectData", selectDataJson);
		}
		
		User user=new User();
		model.addAttribute("user", user);
		model.addAttribute("tcourses", tcourses);
		return "modules/zx/course/listUser";
	}
	@PostMapping(value = "authUser")
	@ResponseBody
	public String authUser(Tcourses tcourses,HttpServletRequest request,HttpServletResponse response) {
		String[] parameterValues = request.getParameterValues("userIds");
		String id=request.getParameter("id");
		TcourseAuthorization tcours=new TcourseAuthorization();
		tcours.setCourseId(id);
		//课程下的所有授权数据
		List<TcourseAuthorization> findList = tcourseAuthorizationService.findList(tcours);
		Map<String,TcourseAuthorization> oldList=new HashMap<String, TcourseAuthorization>(); //一个用户对应的 授权数据
		for(TcourseAuthorization auth: findList){
			oldList.put(auth.getUserId(),auth);
		}
		List<String> currentList=new ArrayList<>();
		if(parameterValues!=null){
			for(String userId:parameterValues){
				currentList.add(userId);
				if(!oldList.containsKey(userId)){
					TcourseAuthorization tcours2=new TcourseAuthorization();
					tcours2.setCourseId(id);		
					tcours2.setUserId(userId);
					tcourseAuthorizationService.save(tcours2);
					try {
						ZxMsgPush zxMsgPush=new ZxMsgPush();
						zxMsgPush.setSendDate(new Date());
						zxMsgPush.setReceiveCode(userId);
						zxMsgPush.setMsgTitle("好消息");
						zxMsgPush.setMsgContent("您有一门新的课程可以学习:《"+tcourses.getCourseTitle()+"》");
						zxMsgPush.setReadStatus("0");
						zxMsgPushService.save(zxMsgPush);
						String sendUserCode = zxMsgPush.getReceiveCode();
						 ZxMsgPush entity=new ZxMsgPush();
						 entity.setReceiveCode(sendUserCode);
						 entity.setReadStatus("0");
						long findCount = zxMsgPushService.findCount(entity);
						SocketMessage sm=new SocketMessage();
						sm.setType("courseinfo");
						sm.setNum(findCount);
						sm.setUserId(sendUserCode);
						jmsMessagingTemplate.convertAndSend(queue,JsonMapper.toJson(sm));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		for(String key:oldList.keySet()){
			if(!currentList.contains(key)){
				TcourseAuthorization tcourseAuthorization = oldList.get(key);
				tcourseAuthorizationService.delete(tcourseAuthorization);
			}
		}
		return renderResult(Global.TRUE, text("保存课程表成功！"));
	}
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("zx:course:tcourses:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<Tcourses> listData(Tcourses tcourses) {
		if (StringUtils.isBlank(tcourses.getParentCode())) {
			tcourses.setParentCode(Tcourses.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(tcourses.getCourseTitle())){
			tcourses.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tcourses.getCourseSimple())){
			tcourses.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tcourses.getCourseCover())){
			tcourses.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tcourses.getCourseContent())){
			tcourses.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tcourses.getCourseLabel())){
			tcourses.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tcourses.getCourseItem())){
			tcourses.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tcourses.getTeacherLoginCode())){
			tcourses.setParentCode(null);
		}
		if (tcourses.getCoursePrice() != null){
			tcourses.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tcourses.getTeacherId())){
			tcourses.setParentCode(null);
		}
		if (tcourses.getLikeNum() != null){
			tcourses.setParentCode(null);
		}
		if (tcourses.getCourseExplain() != null){
			tcourses.setParentCode(null);
		}
		if (tcourses.getLookNum() != null){
			tcourses.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tcourses.getRemarks())){
			tcourses.setParentCode(null);
		}
		List<Tcourses> list = tcoursesService.findList(tcourses);
		return list;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("zx:course:tcourses:view")
	@RequestMapping(value = "form")
	public String form(Tcourses tcourses, Model model,HttpServletRequest request,HttpServletResponse response) {
		// 创建并初始化下一个节点信息
		tcourses = createNextNode(tcourses);

		String courseExplain=request.getParameter("courseExplain");

		if(StringUtils.isNotBlank(courseExplain)){
			if(courseExplain.equals("0")){
				TcourseAuthorization auth=new TcourseAuthorization();
				auth.setCourseId(tcourses.getId());
				List<TcourseAuthorization> authList = tcourseAuthorizationService.findList(auth);
				StringBuilder userCodes=new StringBuilder();
				StringBuilder userNames=new StringBuilder();
				String userCode="";
				String userName="";
				for(TcourseAuthorization aumod:authList){
					if(userCodes.length()>0){
						userCodes.append(",");
						userNames.append(",");
					}
					userCode=aumod.getUserId();
					userName=aumod.getUserName();
					userCodes.append(userCode);
					userNames.append(userName);
				}
				tcourses.setUserCode(userCodes.toString());
				tcourses.setUserName(userNames.toString());
				ZxUser zx=new ZxUser();
				zx.setIdentity("teacher");
				List<ZxUser> findList2 = zxUserService.findList(zx);
				model.addAttribute("teacherList", findList2);
				// 获取岗位列表
				Post post = new Post();
				model.addAttribute("postList", postService.findList(post));
			}
			model.addAttribute("tcourses", tcourses);
			return "modules/zx/course/tcoursesForm"+courseExplain;
		}
		model.addAttribute("tcourses", tcourses);
		return "modules/zx/course/tcoursesForm";
	}


	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("zx:course:tcourses:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public Tcourses createNextNode(Tcourses tcourses) {
		if (StringUtils.isNotBlank(tcourses.getParentCode())){
			tcourses.setParent(tcoursesService.get(tcourses.getParentCode()));
		}
		if (tcourses.getIsNewRecord()) {
			Tcourses where = new Tcourses();
			where.setParentCode(tcourses.getParentCode());
			Tcourses last = tcoursesService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				tcourses.setTreeSort(last.getTreeSort() + 30);
				tcourses.setId(IdGen.nextCode(last.getId()));
			}else if (tcourses.getParent() != null){
				tcourses.setId(tcourses.getParent().getId() + "001");
			}
		}
		// 以下设置表单默认数据
		if (tcourses.getTreeSort() == null){
			tcourses.setTreeSort(Tcourses.DEFAULT_TREE_SORT);
		}
		return tcourses;
	}

	/**
	 * 保存课程表
	 */
	@RequiresPermissions("zx:course:tcourses:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Tcourses tcourses,HttpServletRequest request,HttpServletResponse response) {
		
		tcoursesService.save(tcourses);
		/*Integer courseExplain=tcourses.getCourseExplain();
		if(courseExplain!=null&&courseExplain==0){ //课程说明0代表课程；1表示课时
			TcourseAuthorization author=new TcourseAuthorization();
			author.setCourseId(tcourses.getId());
			List<TcourseAuthorization> findList = tcourseAuthorizationService.findList(author);
			for(TcourseAuthorization tauth:findList){
				tcourseAuthorizationService.delete(tauth);
			}
		}*/
		
		return renderResult(Global.TRUE, text("保存课程表成功！"));
	}


	/**
	 * 查看编辑问题表单 新增的时候  courseId 为课时的id 编辑的时候为问题id
	 */
	@RequiresPermissions("zx:course:tcourses:view")
	@RequestMapping(value = "questionForm")
	public String questionForm(TquestionBank tquestionBank, @RequestParam(name = "courseId") String courseId,
							   @RequestParam(name = "isNewRecord") boolean isNewRecord,
							   @RequestParam(name = "questId",required = false) String questionId, Model model) {
		Post post = new Post();
		model.addAttribute("postList", postService.findList(post));
        if (!isNewRecord){
			tquestionBank = tquestionBankService.get(questionId);
		}
		model.addAttribute("tquestionBank", tquestionBank);
		model.addAttribute("courseId", courseId);
		model.addAttribute("isNewRecord",isNewRecord);
		return "modules/zx/course/tcoursesForm4";
	}

	/**
	 * 保存课程问题
	 *//*
	@RequiresPermissions("zx:course:tcourses:edit")
	@PostMapping(value = "saveQuestionBank")
	@ResponseBody
	public String saveQuestionBank(@Validated TquestionBank tquestionBank, @RequestParam(name = "courseId") String courseId, HttpServletRequest request, HttpServletResponse response) {
		tquestionBankService.saveCourseQuestion(tquestionBank,courseId);
		return renderResult(Global.TRUE, text("保存成功！"));
	}*/

	/**
	 * 停用课程表
	 */
	@RequiresPermissions("zx:course:tcourses:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(Tcourses tcourses) {
		Tcourses where = new Tcourses();
		where.setStatus(Tcourses.STATUS_NORMAL);
		where.setParentCodes("," + tcourses.getId() + ",");
		List<Tcourses> disableList = tcoursesService.findList(where);
		if (disableList!=null && disableList.size()>0){
			disableList.forEach(item->{
				item.setStatus(Tcourses.STATUS_DISABLE);
				tcoursesService.updateStatus(item);
			});
		}
		tcourses.setStatus(Tcourses.STATUS_DISABLE);
		tcoursesService.updateStatus(tcourses);
		return renderResult(Global.TRUE, text("停用课程表成功"));
	}
	
	/**
	 * 启用课程表
	 */
	@RequiresPermissions("zx:course:tcourses:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(Tcourses tcourses) {
		tcourses.setStatus(Tcourses.STATUS_NORMAL);
		tcoursesService.updateStatus(tcourses);
		return renderResult(Global.TRUE, text("启用课程表成功"));
	}
	
	/**
	 * 删除课程表
	 */
	@RequiresPermissions("zx:course:tcourses:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(Tcourses tcourses) {
		Tcourses where = new Tcourses();
		where.setParentCodes("," + tcourses.getId() + ",");
		long count = tcoursesService.findCount(where);
		if (count>0){
			return renderResult(Global.FALSE, text("课程表下面含有未删除的子课程！"));
		}
		tcoursesService.delete(tcourses);
		return renderResult(Global.TRUE, text("删除课程表成功！"));
	}

	/**
	 * 删除课程表
	 *//*
	@RequiresPermissions("zx:course:tcourses:edit")
	@RequestMapping(value = "deleteQuestion")
	@ResponseBody
	public String deleteQuestion(@RequestParam(name = "id") String courseId,
								 @RequestParam(name = "questId") String questionId) {

		TquestionBank tquestionBank = tquestionBankService.get(questionId);
		//删除题库
		if (tquestionBank != null){
			tquestionBankService.delete(tquestionBank);
			TquestionCourse tquestionCourse = new TquestionCourse();
			tquestionCourse.setQuestionId(questionId);
			TquestionCourse tquestion = tquestionCourseService.get(tquestionCourse);
			//删除关系表
			if (tquestion!=null){
				tquestionCourseService.delete(tquestion);
			}
		}
		//删除题库数据
		Tcourses  tcourses = tcoursesService.get(courseId);
		tcoursesService.delete(tcourses);
		return renderResult(Global.TRUE, text("删除问题成功！"));
	}*/


	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("zx:course:tcourses:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		List<Tcourses> list = tcoursesService.findList(new Tcourses());
		for (int i=0; i<list.size(); i++){
			Tcourses e = list.get(i);
			// 过滤非正常的数据
			if (!Tcourses.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getId(), e.getCourseTitle()));
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("zx:course:tcourses:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(Tcourses tcourses){
		if (!UserUtils.getUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		tcoursesService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}
	/**
	 * 下载导入用户数据模板
	 */
	@RequiresPermissions("zx:course:tcourses:view")
	@RequestMapping(value = "importTemplate")
	public void importTemplate(Tcourses tcourses,HttpServletRequest request,HttpServletResponse response) {
		tcourses.setPage(new Page<>(request, response));
		Page<Tcourses> findPage = tcoursesService.findPage(tcourses);
		List<Tcourses> findList = findPage.getList();
		String fileName = "课程数据模板.xlsx";
		try(ExcelExport ee = new ExcelExport("课程数据", Tcourses.class, Type.IMPORT)){
			ee.setDataList(findList).write(response, fileName);
		}
	}

	/**
	 * 导出数据
	 */
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "exportData")
	public void exportData(Tcourses tcourses, Boolean isAll, String ctrlPermi, HttpServletResponse response) {
		tcourses.setIsQueryChildren(true);
		List<Tcourses> list = tcoursesService.findList(tcourses);
		String fileName = "课程数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try(ExcelExport ee = new ExcelExport("课程表数据", Tcourses.class)){
			ee.setDataList(list).write(response, fileName);
		}
	}


}